<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>用户编辑</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        .popup-container {
            padding: 20px;
        }

        .form-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }

        .form-footer {
            border-top: 1px solid #eee;
            padding-top: 20px;
            margin-top: 30px;
            text-align: center;
        }

        .role-checkbox-group {
            max-height: 150px;
            overflow-y: auto;
            border: 1px solid #e6e6e6;
            padding: 10px;
            border-radius: 2px;
            background: #fafafa;
        }

        .layui-form-label {
            width: 100px;
        }

        .layui-input-block {
            margin-left: 130px;
        }
    </style>
</head>

<body>
    <div class="popup-container">
        <form class="layui-form" lay-filter="userForm">
            <input type="hidden" name="id" id="userId">

            <div class="layui-form-item">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="user_name" lay-verify="required" placeholder="请输入用户真实姓名" autocomplete="off"
                        class="layui-input" id="userNameInput">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">用户账号</label>
                <div class="layui-input-block">
                    <input type="text" name="user_id" lay-verify="required" placeholder="点击生成账号" autocomplete="off"
                        class="layui-input" id="userIdInput" >
                    <div class="layui-form-mid">
                        <a href="javascript:void(0)" onclick="generateUserId()" id="generateBtn">点击生成拼音账号</a>
                        <span id="generateStatus"></span>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">所属组织</label>
                <div class="layui-input-block">
                    <select name="org_code" lay-verify="required" lay-search id="orgSelect">
                        <option value="">请选择所属组织</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">用户角色</label>
                <div class="layui-input-block">
                    <div class="role-checkbox-group" id="roleCheckboxGroup">
                        <!-- 角色复选框将通过JS动态生成 -->
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">登录密码</label>
                <div class="layui-input-block">
                    <div class="layui-form-mid layui-word-aux">

                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">账号状态</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="is_active" lay-skin="switch" lay-text="启用|禁用" checked>
                </div>
            </div>

            <div class="form-footer">
                <button type="button" class="layui-btn" lay-submit lay-filter="userSubmit">提交保存</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closePopup()">取消</button>
                <button type="reset" class="layui-btn layui-btn-normal">重置表单</button>
            </div>
        </form>
    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        layui.use(['form', 'layer'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;

            let isEditMode = false;
            let currentUserId = '';

            // 页面加载初始化
            initPage();

            // 表单验证
            form.verify({
                pass: function (value) {
                    if (!isEditMode && !value) {
                        return '添加用户时必须设置密码';
                    }
                    if (value && (value.length < 6 || value.length > 12)) {
                        return '密码必须6到12位';
                    }
                }
            });

            // 表单提交
            form.on('submit(userSubmit)', function (data) {
                submitForm(data.field);
                return false;
            });

            function updatePasswordHint() {
                const hintElement = $('.layui-form-item .layui-form-mid.layui-word-aux');
                if (hintElement.length > 0) {
                    if (isEditMode) {
                        hintElement.text('（用户可自行修改密码，或使用密码重置功能）');
                    } else {
                        hintElement.text('新用户初始密码设置为系统默认密码，建议用户首次登录后修改');
                    }
                }
            }

            function initPage() {
                // 获取URL参数
                const urlParams = new URLSearchParams(window.location.search);
                const userId = urlParams.get('id');

                // 先设置模式和标题
                if (userId) {
                    isEditMode = true;
                    currentUserId = userId;
                    document.title = '编辑用户';
                } else {
                    document.title = '添加用户';
                }

                // 立即更新密码提示
                updatePasswordHint();

                // 加载组织列表和角色列表
                loadOrgList(function () {
                    loadRoleList(function () {
                        if (userId) {
                            // 编辑模式：加载用户数据
                            loadUserData(userId, function () {
                                completeInit();
                            });
                        } else {
                            // 添加模式：直接完成初始化
                            completeInit();
                        }
                    });
                });
            }

            function completeInit() {
                // 通知父窗口调整弹窗大小
                setTimeout(() => {
                    if (window.utils && window.utils.notifyParentResize) {
                        window.utils.notifyParentResize({
                            minWidth: 600,
                            minHeight: 500,
                            extraWidth: 50,
                            extraHeight: 120
                        });
                    }
                }, 100);
            }

            // 加载组织列表
            function loadOrgList(callback) {
                http.get(API_CONFIG.ENDPOINTS.GET_ORG_LIST)
                    .then(function (response) {
                        if (response.data) {
                            renderOrgSelect(response.data);
                            if (callback) callback();
                        } else {
                            layer.msg('组织列表数据为空', { icon: 2 });
                            if (callback) callback();
                        }
                    })
                    .catch(function (error) {
                        console.error('加载组织列表失败:', error);
                        layer.msg('加载组织列表失败: ' + (error.msg || error.message), { icon: 2 });
                        if (callback) callback();
                    });
            }

            function renderOrgSelect(orgList) {
                const select = document.getElementById('orgSelect');

                if (!select) {
                    return;
                }

                if (!orgList || !Array.isArray(orgList) || orgList.length === 0) {
                    select.innerHTML = '<option value="">暂无组织数据</option>';
                    return;
                }

                // 清空现有选项（保留第一个提示选项）
                const firstOption = select.options[0];
                select.innerHTML = '';
                if (firstOption) {
                    select.appendChild(firstOption);
                }

                // 添加组织选项
                orgList.forEach(org => {
                    const option = document.createElement('option');
                    option.value = org.org_code || org.value || org.id || '';
                    option.textContent = org.org_name || org.name || org.text || '未知组织';
                    select.appendChild(option);
                });

                // 重新渲染layui表单
                form.render('select');
            }

            // 加载角色列表
            function loadRoleList(callback) {
                http.get(API_CONFIG.ADMIN.ROLES)
                    .then(function (res) {
                        const roleGroup = document.getElementById('roleCheckboxGroup');

                        roleGroup.innerHTML = '';
                        if (res.data && Array.isArray(res.data)) {
                            res.data
                                .filter(role => role.role_id !== 'admin')  // 先过滤掉 admin 角色
                                .forEach(role => {
                                    //if (role.role_id === 'admin') return;
                                    const checkbox = document.createElement('input');
                                    checkbox.type = 'checkbox';
                                    checkbox.name = 'roles';
                                    checkbox.value = role.role_id;
                                    checkbox.title = role.role_name;
                                    checkbox.setAttribute('lay-skin', 'primary');

                                    const label = document.createElement('div');
                                    label.className = 'layui-inline';
                                    label.style.marginRight = '10px';
                                    label.style.marginBottom = '5px';
                                    label.appendChild(checkbox);

                                    roleGroup.appendChild(label);
                                });

                            form.render('checkbox');
                        }
                        if (callback) callback();
                    })
                    .catch(function (error) {
                        console.error('加载角色列表失败:', error);
                        if (callback) callback();
                    });
            }

            // 加载用户数据（编辑模式）
            function loadUserData(userId, callback) {
                http.get(API_CONFIG.ADMIN.USERS + '/' + userId)
                    .then(function (res) {
                        const user = res.data;

                        // 填充表单数据
                        $('#userId').val(user.id || '');
                        $('#userNameInput').val(user.user_name || '');
                        $('#userIdInput').val(user.user_id || '');
                        $('#orgSelect').val(user.org_code || '');

                        // 设置角色
                        if (user.roles && Array.isArray(user.roles)) {
                            user.roles.forEach(roleId => {
                                const checkbox = $('input[name="roles"][value="' + roleId + '"]');
                                if (checkbox.length > 0) {
                                    checkbox[0].checked = true;
                                }
                            });
                        }

                        // 设置账号状态
                        if (user.is_active !== undefined) {
                            $('input[name="is_active"]')[0].checked = user.is_active;
                        }

                        // 编辑模式下账号不可生成，密码可选填
                        $('#generateBtn').hide();
                        $('#userIdInput').prop('readonly', true);
                        showPasswordTip(true);

                        form.render();

                        if (callback) callback();
                    })
                    .catch(function (error) {
                        console.error('加载用户数据失败:', error);
                        if (callback) callback();
                    });
            }

            // 生成用户账号
            window.generateUserId = function () {
                const userName = $('#userNameInput').val().trim();

                if (!userName) {
                    layer.msg('请先输入用户姓名', { icon: 2 });
                    return;
                }

                $('#generateStatus').html('<span style="color: #1E9FFF;">生成中...</span>');

                http.get(API_CONFIG.ADMIN.GENERATE_USER_ID, { new_name: userName })
                    .then(function (res) {
                        $('#userIdInput').val(res.data);
                        $('#generateStatus').html('<span style="color: #5FB878;">生成成功</span>');
                    })
                    .catch(function (error) {
                        console.error('生成用户账号失败:', error);
                        $('#generateStatus').html('<span style="color: #FF5722;">生成失败</span>');
                        layer.msg('生成账号失败: ' + (error.msg || error.message), { icon: 2 });
                    });
            }

            // 提交表单
            function submitForm(formData) {
                // 处理角色数据
                const roles = [];
                $('input[name="roles"]:checked').each(function () {
                    roles.push(this.value);
                });

                // 构建基础数据结构
                const baseData = {
                    user: {
                        user_id: formData.user_id,
                        user_name: formData.user_name,
                        org_code: formData.org_code
                    },
                    roles: roles
                };

                // 添加模式需要密码
                if (!isEditMode) {
                    baseData.user.password = '123456';
                } else {
                    baseData.user.password = '';
                }

                // 编辑模式可能需要包含用户ID
                if (isEditMode) {
                    baseData.user.id = parseInt($('#userId').val()) || 0;
                }

                var requestPromise;
                if (isEditMode) {
                    requestPromise = http.put(API_CONFIG.ADMIN.USERS + '/' + currentUserId, baseData);
                } else {
                    requestPromise = http.post(API_CONFIG.ADMIN.USERS, baseData);
                }

                requestPromise
                    .then(function (response) {
                        layer.msg(isEditMode ? '用户更新成功' : '用户添加成功', {
                            icon: 1,
                            time: 1500,
                            end: function () {
                                if (window.parent) {
                                    window.parent.postMessage({
                                        type: 'userSaved',
                                        success: true,
                                        isEdit: isEditMode
                                    }, '*');
                                }
                                closePopup();
                            }
                        });
                    })
                    .catch(function (error) {
                        console.error('提交表单失败:', error);
                        layer.msg('操作失败: ' + (error.msg || error.message), { icon: 2 });
                    });
            }
            // 显示密码提示
            function showPasswordTip(show) {
                $('#passwordTip').toggle(show);
                if (!show) {
                    $('#passwordInput').val('123456');
                }
            }

            // 关闭弹窗
            window.closePopup = function () {
                if (window.parent && window.parent.layer) {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                }
            }

            // 供父窗口调用的保存检查函数
            window.hasUnsavedChanges = function () {
                const userName = $('#userNameInput').val();
                return !!userName;
            };

            window.saveData = function (callback) {
                form.on('submit(userSubmit)', function (data) {
                    submitForm(data.field);
                    if (callback) callback(true);
                    return false;
                });
                // 触发提交
                $('button[lay-submit]').click();
            };
        });
    </script>
</body>

</html>